package com.jackrain.clouddata.sys.Listenter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.util.TypeUtils;
import com.jackrain.nea.core.db.Tools;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.web.query.QueryEngine;
import jdk.internal.dynalink.support.TypeUtilities;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;

/**
 * by bigzhi
 */
@Component("com.jackrain.clouddata.sys.Listenter.SupMessageProcess")
@Slf4j
public class SupMessageProcess implements MessageProcess {

    @Override
    public void process(Object paramObject, String tag) throws Exception{
        JSONObject paramJson = JSONObject.parseObject(paramObject.toString());
        try{
            if(paramJson != null && paramJson.size()>0){ //判空 和 size
                updateSup(paramJson,tag);
            }
        }catch(Exception e){
            throw e;
        }
    }

    private void updateSup(JSONObject paramJson,String tag){
        log.info("============insertOrUpdateSup=============");

        //根据tag获取公司ID
        String clientIdSql = "SELECT AD_CLIENT_ID FROM OMS_TAG WHERE ISACTIVE='Y' AND TAGNAME = ?";
        JSONObject clientJson = QueryEngine.getInstance().doQueryObject(clientIdSql,new Object[]{tag});
        if (clientJson == null){
            throw new NDSException("公司ID未找到!");
        }
        Long clientId = clientJson.getLong("AD_CLIENT_ID");

        //获取表名NAME
        String tableName = paramJson.getString("name");
        //获取结果Array
        JSONArray paramArray = paramJson.getJSONArray("value");

        int m=0,n=0;
        boolean insert=false,update=false;

        String selectSql = "SELECT COUNT(1) FROM "+tableName+" WHERE AD_CLIENT_ID=? AND SUPCODE=?";
        String updateSql = null;
        String insertSql = null;

        JSONArray insertArray = new JSONArray();
        JSONArray updateArray = new JSONArray();

        for (int i=0;i<paramArray.size();i++){
            JSONObject jsonObject = paramArray.getJSONObject(i);
            JSONObject omsJson = JSON.parseObject(JSON.toJSONString(jsonObject,new SerializerFeature[]{SerializerFeature.WriteMapNullValue}), Feature.OrderedField);

            for (int l = 0; l < omsJson.keySet().size(); l++) {
                String key = (String) omsJson.keySet().toArray()[l];
                if (key.contains("DATE") && omsJson.get(key) != null) {
                    omsJson.put(key, TypeUtils.castToDate(omsJson.get(key)));
                }
            }
//            omsJson.put("MODIFIEDDATE",new Timestamp(System.currentTimeMillis()));
            omsJson.put("MODIFIEDDATE",new Timestamp(System.currentTimeMillis()));
            omsJson.put("AD_CLIENT_ID",clientId);

            //去重
            int count=QueryEngine.getInstance().doQueryInt(selectSql, new Object[]{omsJson.getInteger("AD_CLIENT_ID"),omsJson.getString("SUPCODE")});
            if(count > 0){//更新
                //调换SUPCODE位置
                String supCode = (String )omsJson.get("SUPCODE");
                omsJson.remove("SUPCODE");
                omsJson.put("SUPCODE",supCode);

                //生成updateSql语句
                if(!update){
                    StringBuffer sb = new StringBuffer( "UPDATE "+tableName+" SET " );//updateSql语句
                    for (String s:omsJson.keySet()) {
                        if(s.equals("AD_CLIENT_ID")){
                            sb.deleteCharAt(sb.length()-1);
                            sb.append(" WHERE " + s + "=? AND " );
                        }else if(s.equals("SUPCODE")){
                            sb.append( s + "=?" );
                        }else{
                            sb.append( s + "=?," );
                        }
                    }
                    updateSql = sb.toString();
                    update = true;
                }

                updateArray.set(m++,omsJson);

            }else{//插入
                omsJson.put("ID", Tools.getSequence(tableName));  //ID

                //生成insertaSql语句
                if(!insert){
                    StringBuffer sb = new StringBuffer("INSERT INTO "+tableName+ "(");//insertaSql语句
                    StringBuffer q = new StringBuffer();//占位符？

                    for (String s:omsJson.keySet()) {
                        if(s.equals("ID")){
                            q.append( "?" );
                            sb.append( s +") VALUES(" + q.toString() + ")" );
                        }else{
                            sb.append( s + "," );
                            q.append( "?," );
                        }
                    }
                    insertSql = sb.toString();
                    insert = true;
                }

                insertArray.set(n++,omsJson);
            }
        }

        if(update){
            QueryEngine.getInstance().executeBatchUpdate(updateSql,updateArray);//批量更新
        }
        if(insert){
            QueryEngine.getInstance().executeBatchUpdate(insertSql,insertArray);//批量插入
        }

    }
}
